package com.zhongjian.technologycal.mall.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.web.ForgetPasswordActivity;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.CodeBean;
import com.zhongjian.technologycal.mall.bean.CodeResBean;
import com.zhongjian.technologycal.mall.bean.LoginBean;
import com.zhongjian.technologycal.mall.http.BaseSubscriber;
import com.zhongjian.technologycal.mall.http.ExceptionHandle;
import com.zhongjian.technologycal.mall.http.MyApiService;
import com.zhongjian.technologycal.mall.http.RetrofitClient;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.Countdown;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.MD5Util;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.utils.ValidatorUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;


/**
 * Created by wei on 2017/9/25.
 * 登录页面的实现
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.login_et_phone)
    EditText login_et_phone;
    @BindView(R.id.login_et_password)
    EditText login_et_password;
    @BindView(R.id.password_ll_login)
    LinearLayout password_ll_login;
    @BindView(R.id.code_ll_login)
    LinearLayout code_ll_login;
    @BindView(R.id.code_tv_login)
    TextView code_tv_login;
    @BindView(R.id.login_et_code)
    EditText login_et_code;
    @BindView(R.id.login_tv_send_code)
    TextView login_tv_send_code;
    private boolean isSelect = true;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    protected void beforeInit() {
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("登录");

    }

    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    @Override
    public void initPresenter() {

    }

    /**
     * 登录提交
     */
    @OnClick(R.id.login_tv_commit)
    public void onClickLoginCommit() {
        if(isSelect){
            if(!NetWorkUtils.isNetConnected(getBaseContext())){
                ToastUitl.showShort(R.string.no_net);
                return;
            }else{

                if(TextUtils.isEmpty(login_et_phone.getText().toString().trim())){
                    ToastUitl.showShort("手机号不能为空～");
                    return;
                }else if(!ValidatorUtils.isMobile(login_et_phone.getText().toString().trim())){
                    ToastUitl.showShort("手机号不格式不正确～");
                    return;
                }else if(TextUtils.isEmpty(login_et_password.getText().toString().trim())){
                    ToastUitl.showShort("密码不能为空～");
                    return;
                }else{
                    MyApiService service = RetrofitClient.getInstance(LoginActivity.this).create(MyApiService.class);
                    Map<String, String> maps = new HashMap<String, String>();
                    maps.put("phoneNum", login_et_phone.getText().toString().trim());
                    maps.put("password", login_et_password.getText().toString().trim());
                    RequestBody body = RequestBody.create(
                            okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
                    // execute and add observable to RxJava
                    RetrofitClient.getInstance(LoginActivity.this).createBaseApi().execute(
                            service.jsonLoginSystem(body), new BaseSubscriber<LoginBean>(LoginActivity.this) {
                                @Override
                                public void onStart() {
                                    super.onStart();
                                }

                                @Override
                                public void onError(ExceptionHandle.ResponeThrowable e) {
                                    Log.e("Lyk", e.getMessage());

                                }

                                @Override
                                public void onNext(LoginBean loginBean) {
                                    if(loginBean.getError_code()==0){
                                        ToastUitl.showShort(loginBean.getError_message());
                                        UserUtils.setUserToken(loginBean.getData());
                                        JPushInterface.setAlias(getBaseContext(),1, MD5Util.encrypt32(loginBean.getData()));
                                        finish();
                                    }else if(loginBean.getError_code()==1){
                                        ToastUitl.showShort(loginBean.getError_message());
                                    }else{
                                        ToastUitl.showShort(loginBean.getError_message());
                                    }

                                }
                            });
                }

            }



        }else{

            if(!NetWorkUtils.isNetConnected(getBaseContext())){
                ToastUitl.showShort(R.string.no_net);
                return;
            }else if(TextUtils.isEmpty(login_et_phone.getText().toString().trim())){
                ToastUitl.showShort("电话号码不能为空～");
                return;
            }else if(TextUtils.isEmpty(login_et_code.getText().toString())){
                ToastUitl.showShort("验证码不能为空～");
                return;
            }else{
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("phoneNum", login_et_phone.getText().toString().trim());
                maps.put("verifyCode", login_et_code.getText().toString().trim());
                RequestBody body = RequestBody.create(
                        okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
                HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestCodeLogin(body, new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Gson gson = new Gson();
                            CodeResBean codeBean = gson.fromJson(responseBody.string(),CodeResBean.class);
                            if(codeBean.getError_code() == 0){
                                ToastUitl.showShort(codeBean.getError_message());
                                UserUtils.setUserToken(codeBean.getData());
                                JPushInterface.setAlias(getBaseContext(),1, MD5Util.encrypt32(codeBean.getData()));
                                finish();
                            }else{
                                ToastUitl.showShort(codeBean.getError_message());
                            }

                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });


            }


        }



    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("TAG", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("TAG", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    break;
                default:
                    logs = "Failed with errorCode = " + code;

            }

        }
    };

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    /**
     * 注册新用户
     */
    @OnClick(R.id.login_tv_register)
    public void onClickRegister() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), RegisterActivity.class);
        this.startActivity(intent);
    }

    /**
     * 忘记密码
     */
    @OnClick(R.id.login_tv_forget_password)
    public void onClickForgetPassword(){
      Intent intent = new Intent();
      intent.setClass(getBaseContext(), ForgetPasswordActivity.class);
      startActivity(intent);
    }

    @OnClick(R.id.code_tv_login)
    public void onClickCodeLogin(){
        if(isSelect){
            code_ll_login.setVisibility(View.VISIBLE);
            password_ll_login.setVisibility(View.GONE);
            isSelect = false;
            code_tv_login.setText("密码登录");

        }else {
            password_ll_login.setVisibility(View.VISIBLE);
            code_ll_login.setVisibility(View.GONE);
            isSelect = true;
            code_tv_login.setText("短信验证码登录");
        }

    }

    @OnClick(R.id.login_tv_send_code)
    public void onClickLoginCode(){
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;

        } else {
            if (TextUtils.isEmpty(login_et_phone.getText().toString().trim())) {
                ToastUitl.showShort("手机号不能为空～");
                return;
            } else if (!ValidatorUtils.isMobile(login_et_phone.getText().toString().trim())) {
                ToastUitl.showShort("手机号格式不正确～");
                return;
            } else {
                new Countdown(login_tv_send_code, 30, "秒后重试", false);
                login_tv_send_code.setClickable(false);
                MyApiService service = RetrofitClient.getInstance(LoginActivity.this).create(MyApiService.class);
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("phoneNum", login_et_phone.getText().toString().trim());
                RequestBody body = RequestBody.create(
                        okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));

                // execute and add observable to RxJava
                RetrofitClient.getInstance(LoginActivity.this).createBaseApi().execute(
                        service.jsonSendCode(body), new BaseSubscriber<CodeBean>(LoginActivity.this) {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(LoginActivity.this);
                            }

                            @Override
                            public void onError(ExceptionHandle.ResponeThrowable e) {
                                Log.e("Lyk", e.getMessage());

                            }

                            @Override
                            public void onNext(CodeBean codeBean) {
                                if (codeBean.getError_code() == 0) {
                                    ToastUitl.showShort(codeBean.getError_message());

                                } else {
                                    new Countdown(login_tv_send_code, 0, "秒后重试", false);
                                    login_tv_send_code.setClickable(true);
                                    ToastUitl.showShort(codeBean.getError_message());
                                }

                            }

                            @Override
                            public void onCompleted() {
                                super.onCompleted();
                                LoadingDialog.cancelDialogForLoading();
                            }
                        });
            }

        }
    }
}
